package crypto

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"golang.org/x/crypto/ocsp"
	"golang.org/x/crypto/pkcs12"
)

func Pkcs12(source []byte, password string) ([]byte, []byte) {
	privateKey, cert, err := pkcs12.Decode(source, password)
	if err != nil {
		panic(err)
	}

	privateKeyPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(privateKey.(*rsa.PrivateKey)),
	})
	certPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: cert.Raw,
	})

	return privateKeyPEM, certPEM
}
func Pkcs122(source []byte, password string) []*pem.Block {
	data, err := pkcs12.ToPEM(source, password)
	if err != nil {
		panic(err)
	}

	return data
}

func Ocsp(source, issuer []byte) *ocsp.Response {
	cert, err := x509.ParseCertificate(source)
	if err != nil {
		panic(err)
	}

	issuerCert, err := x509.ParseCertificate(issuer)
	if err != nil {
		panic(err)
	}

	req, err := ocsp.CreateRequest(cert, issuerCert, nil)
	if err != nil {
		panic(err)
	}

	res, err := ocsp.ParseResponse(req, issuerCert)
	if err != nil {
		panic(err)
	}

	return res
}
